package com.common.core.results;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.common.core.exception.code.BaseErrorCode;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.io.Serializable;

/**
 * @auther zhangwj
 * @date 2021/7/26 下午3:46
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class SingleResult<T> extends Result implements Serializable {

    private static final long serialVersionUID = 1L;

    SingleResult() {
    }

    @JSONField(ordinal = 5)
    private T payload;

    public static <T> SingleResult<T> of() {
        return Result.singleResult(null);
    }

    public static <T> SingleResult<T> of(T data) {
        return Result.singleResult(data);
    }

    public static <T> SingleResult<T> failed(int errNum, String errMsg) {
        SingleResult<T> response = new SingleResult<>();
        response.setSuccess(false);
        response.setErrNum(errNum);
        response.setErrMsg(errMsg);
        return response;
    }

    public static <T> SingleResult<T> failed(BaseErrorCode errorCode) {
        SingleResult<T> response = new SingleResult<>();
        response.setSuccess(false);
        response.setErrNum(errorCode.getErrNum());
        response.setErrMsg(errorCode.getErrMsg());
        return response;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this, SerializerFeature.WriteMapNullValue);
    }
}
